<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:sa="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>栏目管理</title>
    <link rel="stylesheet" th:href="@{/pear/component/pear/css/pear.css}"/>
    <link rel="stylesheet" th:href="@{/pear/admin/css/other/common.css}"/>
    <!-- 加 载 样 式 -->
    <link rel="stylesheet" th:href="@{/pear/admin/css/loader.css}"/>
    <!-- 布 局 样 式 -->
    <link rel="stylesheet" th:href="@{/pear/admin/css/admin.css}"/>
    <link rel="stylesheet" th:href="@{/pear/admin/css/admin.dark.css}"/>
    <link rel="stylesheet" th:href="@{/pear/admin/css/variables.css}"/>
    <link rel="stylesheet" th:href="@{/pear/admin/css/reset.css}"/>
</head>
<body class="pear-container">
<div class="layui-card">
    <div class="layui-card-header" style="padding: 9px 20px">
        <span style="font-size: 22px">栏目信息</span>
        <button style="float: right;height: inherit" class="layui-btn " id="addChannel"
                sa:hasPermission="channel_add">
            <i class="layui-icon layui-icon-add-1"></i>
            新增栏目
        </button>
    </div>
    <div class="layui-card-body" style="overflow: auto" id="channelBody">
        <form class="layui-form layui-col-md8" action="" style="height: 80vh;padding-left: 60px">
            <div class="layui-form-item">
                <label class="layui-form-label">栏目编号</label>
                <div class="layui-input-block">
                    <input type="text" name="channelId" class="layui-input" id="channelId" disabled>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">栏目浏览量</label>
                <div class="layui-input-block">
                    <input type="text" name="count" class="layui-input" id="count" disabled>
                </div>
            </div>
            <!-- 栏目名称 -->
            <div class="layui-form-item">
                <label class="layui-form-label">栏目名称</label>
                <div class="layui-input-block">
                    <input type="text" name="channelName" lay-verify="required|checkChannelName"
                           placeholder="请输入栏目名称" class="layui-input" maxlength="100" id="channelName">
                    <div id="titleCharCount" class="char-count">0/100</div>
                </div>
            </div>
            <!-- 父级栏目 (树形选择) -->
            <div class="layui-form-item">
                <label class="layui-form-label">父级栏目</label>
                <div class="layui-input-block">
                    <input type="text" id="parent-tree-input" placeholder="请选择父级栏目" class="layui-input"
                           readonly="readonly">
                    <!-- 清空按钮 -->
                    <button type="button" id="clear-parent" class="layui-btn  layui-btn-sm"
                            style="position: absolute; right: 5px; top: 5px;">
                        清空
                    </button>
                    <!-- 用于提交的隐藏字段 -->
                    <input type="hidden" name="parentId" id="parentName"/>
                    <div id="parent-tree"
                         style="display:none; position: absolute; z-index: 1000; background-color: #fff; border: 1px solid #d2d2d2; width: 50%"></div>
                </div>
            </div>
            <!-- 栏目排序 -->
            <div class="layui-form-item">
                <label class="layui-form-label">栏目排序</label>
                <div class="layui-input-block">
                    <input type="number" min="0" max="65535" name="channelSort" placeholder="请输入栏目排序"
                           class="layui-input"
                           id="channelSort" lay-verify="required">
                </div>
            </div>
            <!-- 栏目路径 -->
            <div class="layui-form-item">
                <label class="layui-form-label">栏目路径</label>
                <div class="layui-input-block">
                    <input type="text" name="urlKey" placeholder="请输入栏目路径" class="layui-input"
                           id="urlKey" maxlength="50" lay-verify="required|checkUrlKey">
                    <div id="urlKeyCharCount" class="char-count">0/50</div>
                </div>
            </div>
            <!-- 模版类型 -->
            <div class="layui-form-item">
                <label class="layui-form-label">模板类型</label>
                <div class="layui-input-block" style="display: flex;justify-content: flex-start">
                    <div class="layui-col-md4">
                        <select id="selectType" name="type" lay-verify="required" lay-filter="templateType">
                            <option value="">请选择模板类型</option>
                        </select>
                    </div>
                    <div class="layui-col-md4" style="display:none;" id="templateWrapper">
                        <select id="selectTemplate" name="templateId" lay-filter="template">
                            <option value="">请选择模板</option>
                        </select>
                    </div>
                    <div class="layui-col-md4" style="display:none;" id="infoWrapper">
                        <select id="selectInfo" name="detailTemplate" lay-filter="info">
                            <option value="">请选择文章详细页</option>
                        </select>
                    </div>
                </div>

            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">是否需要审核</label>
                <div class="layui-input-block" id="checkedDiv">
                    <input type="radio" name="isChecked" value="1" title="需要">
                    <input type="radio" name="isChecked" value="2" title="不需要">
                </div>
            </div>
            <div class="layui-form-item" id="channelStruct" style="display: none">
                <label class="layui-form-label">栏目结构</label>
                <div class="layui-input-block">
                    <select id="selectStruct" name="structId" lay-filter="struct">
                    </select>
                </div>
            </div>
            <div style="text-align: center;margin-top: 50px">
                <button type="submit" class="layui-btn layui-btn-success" lay-submit=""
                        lay-filter="submit-channel" style="margin-right: 50px " sa:hasPermission="channel_add">
                    <i class="layui-icon layui-icon-ok"></i>
                    保存
                </button>
                <button type="button" class="layui-btn layui-btn-danger" id="deleteChannel"
                        sa:hasPermission="channel_delete">
                    <i class="layui-icon layui-icon-delete"></i>
                    删除
                </button>
            </div>
        </form>
    </div>
</div>

<script th:src="@{/pear/component/layui/layui.js}"></script>
<script th:src="@{/pear/component/pear/pear.js}"></script>
<script th:inline="javascript">
    layui.use(['form', 'jquery', 'tree'], function () {
        let form = layui.form;
        let $ = layui.jquery;
        let tree = layui.tree;
        let baseURL = /*[[@{/}]]*/ '';
        // 在页面加载时加载初始的 select 选项
        $.ajax({
            url: baseURL + "cms/struct/getStructList",
            type: 'get',
            success: function (res) {
                let select = $('#selectStruct');
                select.empty().append('<option value="0">请选择栏目结构</option>'); // 清空现有的选项
                res.data.forEach(function (option) {
                    select.append('<option value="' + option.structId + '">' + option.name + '</option>');
                });
                form.render('select'); // 重新渲染 select 元素
            }
        });
        // 获取栏目id
        let queryString = window.location.search;
        // 解析查询参数
        let urlParams = new URLSearchParams(queryString);
        const channelId = urlParams.get('channelId');


        if (channelId == null) {
            $('#channelBody').remove();
        } else {
            let removeFlag = true
            $.ajax({
                url: baseURL + "cms/channel/judgeInfoExists",
                type: 'GET',
                data: {
                    channelId: channelId
                },
                success: function (res) {
                    if (res.code === 1000 && res.data === true) {
                        $('#parent-tree-input').prop('disabled', true)
                        $('#clear-parent').prop('disabled', true)
                        $('#urlKey').prop('disabled', true)
                        $('#checkedDiv input[type=radio]').prop('disabled', true)
                        $('#selectInfo').prop('disabled', true)
                        $('#selectTemplate').prop('disabled', true)
                        $('#selectType').prop('disabled', true)
                        removeFlag = false
                    }
                },
                error: function (error) {
                    console.error(error);
                }
            })


            //表单验证
            form.verify({
                checkChannelName: function (value) {
                    if (!new RegExp("^[a-zA-Z\\u4e00-\\u9fa5][a-zA-Z0-9\\u4e00-\\u9fa5\\s]*$").test(value)) {
                        return '栏目名称不能包含特殊字符';
                    }
                },
                checkUrlKey: function (value) {
                    if (!new RegExp("^[a-zA-Z0-9]+$").test(value)) {
                        return '栏目路径只能包含字母和数字';
                    }
                }
            });
            // 输入框长度的动态获取
            $('#channelName').on('input', function () {
                let maxLength = $(this).attr('maxlength');
                let currentLength = $(this).val().length
                $('#titleCharCount').text(currentLength + "/" + maxLength);
            });
            $('#urlKey').on('input', function () {
                let maxLength = $(this).attr('maxlength');
                let currentLength = $(this).val().length;
                $('#urlKeyCharCount').text(currentLength + "/" + maxLength);
            });
            // 初始化树形结构的隐藏状态
            $('#parent-tree').hide();

            // 点击输入框时显示树形结构
            $('#parent-tree-input').on('click', function () {
                $('#parent-tree').toggle(); // 显示或隐藏树形结构
            });

            // 渲染父级栏目树形结构
            $.get(baseURL + "cms/channel/getParentMenus", function (data) {
                let d;
                if (data != null) {
                    d = filterByChannelId(data, channelId)
                }
                tree.render({
                    elem: '#parent-tree', // 树形组件容器
                    data: d, // 后端返回的树形数据
                    click: function (obj) {
                        if (obj && obj.data) {
                            $('#parent-tree-input').val(obj.data.title); // 填充栏目名称
                            $('#parentName').val(obj.data.id); // 填充栏目ID
                            $('#parent-tree').hide(); // 隐藏树形选择框
                        } else {
                            console.error("无法获取节点数据");
                        }
                    }
                });
            });

            // 点击清空按钮时，清空输入框和隐藏树形结构
            $('#clear-parent').on('click', function () {
                $('#parent-tree-input').val(''); // 清空输入框
                $('#parentName').val(0); // 清空隐藏的父级ID
                $('#parent-tree').hide(); // 隐藏树形结构
            });
            // 点击空白区域时，关闭树形选择框
            $(document).on('click', function (e) {
                if (!$(e.target).closest('#parent-tree-input').length && !$(e.target).closest('#parent-tree').length) {
                    $('#parent-tree').hide();
                }
            });

            // 树组件过滤函数
            function filterByChannelId(data, channelId) {
                return data.filter(item => {
                    if (item.id == channelId) {
                        return false;
                    }
                    if (item.children && item.children.length > 0) {
                        item.children = filterByChannelId(item.children, channelId);
                        return true;
                    }
                    return true;
                });
            }

            //下拉框所需参数
            let type = null
            let template = null
            let typeList = null
            let detailTemplate = null
            let detailTemplateValue = null
            //获取当前栏目数据
            $.ajax({
                url: baseURL + "cms/channel/select",
                type: 'GET',
                data: {
                    channelId: channelId
                },
                success: function (res) {
                    console.log(res.data)
                    if (res.code === 1000) {
                        if (res.data.type === 10 || res.data.type === 13) {
                            $('#channelStruct').show() // 使用 jQuery 的 css 方法
                        } else {
                            $('#channelStruct').hide(); // 确保隐藏
                        }
                        $('#channelId').val(res.data.channelId)
                        $('#count').val(res.data.count)
                        $('#channelName').val(res.data.channelName)
                        $('#parent-tree-input').val(res.data.parentName)
                        $('#channelSort').val(res.data.channelSort)
                        $('#urlKey').val(res.data.urlKey)
                        $("input[name=isChecked][value='1']").prop('checked', res.data.isChecked === 1);
                        $("input[name=isChecked][value='2']").prop('checked', res.data.isChecked === 2);
                        $('#selectStruct').val(res.data.structId)
                        form.render('radio');
                        type = res.data.type
                        template = res.data.templateId
                        detailTemplate = res.data.detailTemplate
                        detailTemplateValue = res.data.detailTemplate
                        let maxLength = $('#channelName').attr('maxlength');
                        let currentLength = res.data.channelName.length
                        $('#titleCharCount').text(currentLength + "/" + maxLength);

                        let urlKeyMaxLength = $('#urlKey').attr('maxlength');
                        let urlKeyCurrentLength = res.data.urlKey.length
                        $('#urlKeyCharCount').text(urlKeyCurrentLength + "/" + urlKeyMaxLength);
                        //模板类型下拉框
                        $.ajax({
                            url: baseURL + "cms/template/getTemplateTypeList",
                            type: 'GET',
                            success: function (res) {
                                if (res.code === 1000) {
                                    typeList = res.data
                                    let dropdownData = res.data.map(item => {
                                        return {
                                            "id": item.templateTypeId,
                                            "title": item.typeName
                                        };
                                    });
                                    let selectElem = $('#selectType'); // 下拉框的容器
                                    selectElem.empty();  // 清空下拉框内容
                                    selectElem.append('<option value="">请选择模板类型</option>');
                                    dropdownData.forEach(item => {
                                        selectElem.append(`<option value="${item.id}">${item.title}</option>`);
                                    });
                                    if (type) {
                                        selectElem.val(type)
                                        loadTemplates(type)
                                    }
                                    form.render('select');
                                }
                            },
                            error: function (error) {
                                console.error(error);
                            }
                        })
                    }
                }
            })

            //模板列表下拉框
            function loadTemplates(templateTypeId) {
                let templateSelect = $('#selectTemplate');
                templateSelect.empty(); // 清空模板内容下拉框
                $('#templateWrapper').hide(); // 隐藏模板内容选择框
                $('#selectTemplate').removeAttr('lay-verify');
                form.render('select');
                templateSelect.append('<option value="">请选择模板内容</option>');
                $.ajax({
                    url: baseURL + "cms/template/getListByTypeId",
                    type: 'GET',
                    data: {templateTypeId: templateTypeId},
                    success: function (res) {
                        if (res.code === 1000) {
                            res.data.forEach(item => {
                                templateSelect.append(`<option value="${item.templateId}">${item.templateName}</option>`);
                            });

                            // 如果有选中的模板名称，自动选中模板
                            if (template) {
                                templateSelect.val(template);
                            }

                            // 显示模板内容下拉框
                            $('#templateWrapper').show();
                            $('#selectTemplate').attr('lay-verify', 'required');  // 添加验证
                            form.render('select'); // 渲染模板内容下拉框
                            loadInfo(templateTypeId)
                        }
                    },
                    error: function (error) {
                        console.error(error);
                    }
                });
            }

            //文章详细列表下拉框
            function loadInfo(type) {
                let infoSelect = $('#selectInfo');
                infoSelect.empty();
                $('#infoWrapper').hide();
                $('#selectInfo').removeAttr('lay-verify');  // 移除验证
                form.render('select');  // 重新渲染 select 元素
                let t = typeList.find(item => {
                    if (item.code == "LIST" && item.templateTypeId == type) {
                        return item;
                    }
                });
                if (t) {
                    infoSelect.append('<option value="">请选择文章详细页内容</option>');
                    $.ajax({
                        url: baseURL + "cms/template/getDetailList",
                        type: 'GET',
                        success: function (res) {
                            if (res.code === 1000) {
                                res.data.forEach(item => {
                                    infoSelect.append(`<option value="${item.templateId}">${item.templateName}</option>`);
                                });

                                if (detailTemplate) {
                                    infoSelect.val(detailTemplate);
                                }

                                // 显示模板内容下拉框
                                $('#infoWrapper').show();
                                $('#selectInfo').attr('lay-verify', 'required');  // 添加验证
                                form.render('select'); // 渲染模板内容下拉框
                            }
                        },
                        error: function (res) {
                            console.log(res)
                        }
                    });
                } else {
                    detailTemplate = null
                }
            }

            //下拉框的动态显示
            form.on('select(templateType)', function (data) {
                let selectedTemplateTypeId = data.value;
                // 清空模板内容下拉框并隐藏
                let templateSelect = $('#selectTemplate');
                templateSelect.empty();
                $('#templateWrapper').hide();
                $('#selectTemplate').removeAttr('lay-verify');
                let infoSelect = $('#selectInfo');
                infoSelect.empty();
                $('#infoWrapper').hide();
                $('#selectInfo').removeAttr('lay-verify');  // 移除验证
                if (selectedTemplateTypeId === '10' || selectedTemplateTypeId === '13') {
                    $('#channelStruct').show() // 使用 jQuery 的 css 方法
                } else {
                    $('#channelStruct').hide(); // 确保隐藏
                }
                form.render('select'); // 渲染模板内容下拉框

                if (selectedTemplateTypeId) {
                    $.ajax({
                        url: baseURL + "cms/template/getListByTypeId", // 假设接口返回对应模板内容数据
                        type: 'GET',
                        data: {templateTypeId: selectedTemplateTypeId}, // 传递模板类型ID
                        success: function (res) {
                            if (res.code === 1000) {
                                templateSelect.append('<option value="">请选择模板内容</option>');
                                res.data.forEach(item => {
                                    templateSelect.append(`<option value="${item.templateId}">${item.templateName}</option>`);
                                });
                                // 显示模板内容下拉框并渲染
                                $('#templateWrapper').show();
                                $('#selectTemplate').attr('lay-verify', 'required');  // 添加验证
                                form.render('select'); // 重新渲染模板内容下拉框
                                loadInfo(selectedTemplateTypeId)
                            }
                        },
                        error: function () {
                            layer.msg('服务器异常，请稍后再试！', {icon: 2, time: 2000});
                        }
                    });
                }
            });

            //保存栏目信息
            form.on('submit(submit-channel)', function (data) {
                let loading = layer.load();
                $.ajax({
                    url: baseURL + 'cms/channel/update',
                    data: JSON.stringify(data.field),
                    dataType: 'json',
                    contentType: 'application/json',
                    type: 'post',
                    success: function (result) {
                        layer.close(loading);
                        if (result.code === 1000) {
                            layer.msg(result.msg, {
                                icon: 1,
                                time: 2000
                            }, function () {
                                form.render()
                            })
                        } else {
                            layer.msg(result.msg, {
                                icon: 2,
                                time: 2000
                            })
                        }
                    },
                    error: function () {
                        layer.close(loading);
                        layer.msg('系统错误，请稍后再试！', {
                            icon: 2,
                            time: 2000
                        })
                    }
                })
                return false;
            })
            //删除栏目信息
            $('#deleteChannel').on('click', function () {
                layer.confirm('确定要删除该栏目吗？', {
                    icon: 3,
                    title: '提示'
                }, function (index) {
                    if (!removeFlag) {
                        layer.msg('该栏目下还存在文章信息，请清空后重试！', {
                            icon: 2,
                            time: 2000
                        })
                        return
                    }
                    layer.close(index);
                    let loading = layer.load();
                    $.ajax({
                        url: baseURL + 'cms/channel/delete/' + channelId,
                        dataType: 'json',
                        type: 'post',
                        success: function (result) {
                            layer.close(loading);
                            if (result.code === 1000) {
                                layer.msg(result.msg, {
                                    icon: 1,
                                    time: 2000
                                }, function () {
                                    location.href = "channel_management";
                                })
                            } else {
                                layer.msg(result.msg, {
                                    icon: 2,
                                    time: 2000
                                });
                            }
                        },
                        error: function () {
                            layer.close(loading);
                            layer.msg('系统错误，请稍后再试！', {
                                icon: 2,
                                time: 2000
                            })
                        }
                    })
                });
            })
        }


        //新增栏目信息
        $('#addChannel').on('click', function () {
            layer.open({
                type: 2,
                title: '新增栏目',
                shade: 0.1,
                area: ['900px', '600px'],
                content: 'channel_add'
            });
        })
    });
</script>
</body>
</html>